package liumengbaio.lolzhangyoubao.Activity.Fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import liumengbaio.lolzhangyoubao.Activity.Activity.AllHisttoryActivity;
import liumengbaio.lolzhangyoubao.Activity.Adapter.HistoryAdapter;
import liumengbaio.lolzhangyoubao.Activity.InFo.ChangYongYingXiong;
import liumengbaio.lolzhangyoubao.Activity.InFo.FindHistotySummoner;
import liumengbaio.lolzhangyoubao.Activity.InFo.RecentBattle;
import liumengbaio.lolzhangyoubao.Activity.InFo.ZhanjiGaiLan;
import liumengbaio.lolzhangyoubao.Activity.View.DonutProgress;
import liumengbaio.lolzhangyoubao.Activity.utils.HttpUtils;
import liumengbaio.lolzhangyoubao.R;

/**
 * Created by lanouhn on 16/9/18.
 */
public class MyHistoryFragment extends Fragment {
    private ImageView show_play_icon;
    private TextView tv_show_play_nicker_name, tv_show_play_area, tv_area, tv_show_play_lolname, acount_one, acount_two, acount_three, acount_four, win_acount_one,
            win_acount_two, win_acount_three,tv_to_all_history, win_acount_four, tv_use_num_one, tv_use_num_two, tv_use_num_three, tv_use_num_four, tv_use_num_five, tv_win_num_one, tv_win_num_two, tv_win_num_three, tv_win_num_four, tv_win_num_five;
    private Button btn_model;
    private DonutProgress donutProgress_one, donutProgress_two, donutProgress_three, donutProgress_four;
    private String name = "", area = "", url = "";
    private FindHistotySummoner findHistotySummoner;
    private ZhanjiGaiLan zhanjigailan;
    private ChangYongYingXiong changYongYingXiong;
    private RecentBattle recentBattle;
    private List<ChangYongYingXiong> list;
    private ImageView iv_changyong_one, iv_changyong_two, iv_changyong_three, iv_changyong_four, iv_changyong_five;
    private int flag;
    private String[] server_name = new String[]{"全部大区   ", "艾欧尼亚   ", "祖安   ", "诺克萨斯   ", "班德尔城   ", "皮尔特沃夫   "
            , "战争学院   ", "巨神峰   ", "雷瑟守备   ", "裁决之地   ", "黑色玫瑰   ", "暗影岛   ", "钢铁烈阳   "
            , "均衡教派   ", "水晶之痕   ", "影流   ", "守望之海   ", "征服之海   ", "卡拉曼达   "
            , "皮城警备   ", "比尔吉沃特   ", "德玛西亚   ", "弗雷尔卓德   ", "无畏先锋   ", "恕瑞玛   "
            , "扭曲丛林   ", "巨龙之巢   ", "教育网专区   "};
    private String[] server_id = new String[]{"0", "1", "3", "4", "5", "7", "8", "10", "11", "13", "14", "15", "17"
            , "18", "19", "22", "23", "24", "25"
            , "27", "2", "6", "9", "12", "16"
            , "20", "26", "21"};
    private ListView my_history_fragment_listview;
    private HistoryAdapter adapter;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.my_history_fragment, null);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView(getView());
        initData();
    }

    private void initData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    HttpUtils.doPostAsyn("http://lol.magnet.zhangyoubao.com/service/rest?" +
                                    "api=player.info&game=lol&platformVersion=400901&modle_=MX4",
                            "apiVersion=v1&platform=android&os=android&osVersion=19&secretSignature=D4vDIgBCwlLY%2ByXXyPx3oqnjD2Q%3D&game=lol&params%5Brequest%5D=%7B%22uid%22%3A%22%7B%5C%22tgp%5C%22%3A%5C%22U18084499025935679780%5C%22%7D%22%2C%22area%22%3A%226%22%2C%22name%22%3A%22%E5%B3%B0%E5%93%A5%E6%97%A0%E6%95%8C%E5%A6%B9%E5%AD%90%E6%9D%A5%E8%A2%AD%22%2C%22is_current%22%3A1%7D&sign=&platformVersion=400901&time=1474205644&secretId=AKIDz8krbsJ5yKBZQpn74WFkmLPx3gnPhESA&nonce=329443&userToken=1285c08b612411d0bfc35f213eb5d92a73&secretVersion=v1.0&params%5Bver%5D=27&userId=15863305&api=player.info&deviceId=JfoZvarCyLfJIqs9SRFolapk21%2FwEw63JVMaX7Y3v5w%3D&", new HttpUtils.CallBack() {
                                @Override
                                public void onRequestComplete(String result) {
                                    Gson gson = new Gson();
                                    findHistotySummoner = gson.fromJson(result, FindHistotySummoner.class);
                                }
                            }, handler);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    HttpUtils.doPostAsyn("http://lol.magnet.zhangyoubao.com/service/rest?api=player.summary&game=lol&platformVersion=400901&modle_=MX4",
                            "apiVersion=v1&platform=android&os=android&osVersion=19&secretSignature=%2BHg%2BqCxh26asug%2FI%2B9RHRQYm%2FFY%3D&game=lol&params%5Brequest%5D=%7B%22uid%22%3A%22%7B%5C%22tgp%5C%22%3A%5C%22U18084499025935679780%5C%22%7D%22%2C%22area%22%3A%226%22%2C%22name%22%3A%22%E5%B3%B0%E5%93%A5%E6%97%A0%E6%95%8C%E5%A6%B9%E5%AD%90%E6%9D%A5%E8%A2%AD%22%2C%22is_current%22%3A1%7D&sign=&platformVersion=400901&time=1474205644&secretId=AKIDz8krbsJ5yKBZQpn74WFkmLPx3gnPhESA&nonce=720243&userToken=1285c08b612411d0bfc35f213eb5d92a73&secretVersion=v1.0&params%5Bver%5D=27&userId=15863305&api=player.summary&deviceId=JfoZvarCyLfJIqs9SRFolapk21%2FwEw63JVMaX7Y3v5w%3D&",
                            new HttpUtils.CallBack() {
                                @Override
                                public void onRequestComplete(String result) {
                                    Gson gson = new Gson();
                                    zhanjigailan = gson.fromJson(result, ZhanjiGaiLan.class);
                                }
                            }, handler2);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    HttpUtils.doPostAsyn("http://lol.magnet.zhangyoubao.com/service/rest?api=common.useherolist&game=lol&platformVersion=400901&modle_=MX4",
                            "apiVersion=v1&platform=android&os=android&osVersion=19&secretSignature=2F1qyPusLm5VdDoYBY6y7OCjf6c%3D&game=lol&params%5Brequest%5D=%7B%22uid%22%3A%22%7B%5C%22tgp%5C%22%3A%5C%22U18084499025935679780%5C%22%7D%22%2C%22area%22%3A%226%22%2C%22name%22%3A%22%E5%B3%B0%E5%93%A5%E6%97%A0%E6%95%8C%E5%A6%B9%E5%AD%90%E6%9D%A5%E8%A2%AD%22%2C%22is_current%22%3A1%2C%22champion_ids%22%3A%5B51%2C24%2C21%2C45%2C67%5D%7D&sign=&platformVersion=400901&time=1474205646&secretId=AKIDz8krbsJ5yKBZQpn74WFkmLPx3gnPhESA&nonce=76879&userToken=1285c08b612411d0bfc35f213eb5d92a73&secretVersion=v1.0&params%5Bver%5D=27&userId=15863305&api=common.useherolist&deviceId=JfoZvarCyLfJIqs9SRFolapk21%2FwEw63JVMaX7Y3v5w%3D&",
                            new HttpUtils.CallBack() {
                                @Override
                                public void onRequestComplete(String result) {
                                    Gson gson = new Gson();
                                    changYongYingXiong = gson.fromJson(result, ChangYongYingXiong.class);
                                }
                            }, handler3);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    HttpUtils.doPostAsyn("http://lol.magnet.zhangyoubao.com/service/rest?api=match.lastlist&game=lol&platformVersion=400901&modle_=MX4",
                            "apiVersion=v1&platform=android&os=android&osVersion=19&secretSignature=KFn5SNhQ9uDlnWg9%2FX8%2F87RNiAE%3D&game=lol&params%5Brequest%5D=%7B%22uid%22%3A%22%7B%5C%22tgp%5C%22%3A%5C%22U18084499025935679780%5C%22%7D%22%2C%22area%22%3A%226%22%2C%22name%22%3A%22%E5%B3%B0%E5%93%A5%E6%97%A0%E6%95%8C%E5%A6%B9%E5%AD%90%E6%9D%A5%E8%A2%AD%22%2C%22b_type%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22is_current%22%3A1%7D&sign=&platformVersion=400901&time=1474205645&secretId=AKIDz8krbsJ5yKBZQpn74WFkmLPx3gnPhESA&nonce=273338&userToken=1285c08b612411d0bfc35f213eb5d92a73&secretVersion=v1.0&params%5Bver%5D=27&userId=15863305&api=match.lastlist&deviceId=JfoZvarCyLfJIqs9SRFolapk21%2FwEw63JVMaX7Y3v5w%3D&",
                            new HttpUtils.CallBack() {
                                @Override
                                public void onRequestComplete(String result) {
                                    Gson gson = new Gson();
                                    recentBattle = gson.fromJson(result, RecentBattle.class);
                                }
                            }, handler4);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void initView(View view) {
        show_play_icon = (ImageView) view.findViewById(R.id.show_play_icon);
        tv_show_play_nicker_name = (TextView) view.findViewById(R.id.tv_show_play_nicker_name);
        tv_show_play_area = (TextView) view.findViewById(R.id.tv_show_play_area);
        tv_area = (TextView) view.findViewById(R.id.tv_area);
        tv_show_play_lolname = (TextView) view.findViewById(R.id.tv_show_play_lolname);
        btn_model = (Button) view.findViewById(R.id.btn_model);
        acount_one = (TextView) view.findViewById(R.id.acount_one);
        acount_two = (TextView) view.findViewById(R.id.acount_two);
        acount_three = (TextView) view.findViewById(R.id.acount_three);
        acount_four = (TextView) view.findViewById(R.id.acount_four);
        donutProgress_one = (DonutProgress) view.findViewById(R.id.donutProgress_one);
        donutProgress_two = (DonutProgress) view.findViewById(R.id.donutProgress_two);
        donutProgress_three = (DonutProgress) view.findViewById(R.id.donutProgress_three);
        donutProgress_four = (DonutProgress) view.findViewById(R.id.donutProgress_four);
        win_acount_one = (TextView) view.findViewById(R.id.win_acount_one);
        win_acount_two = (TextView) view.findViewById(R.id.win_acount_two);
        win_acount_three = (TextView) view.findViewById(R.id.win_acount_three);
        win_acount_four = (TextView) view.findViewById(R.id.win_acount_four);
        iv_changyong_one = (ImageView) view.findViewById(R.id.iv_changyong_one);
        iv_changyong_two = (ImageView) view.findViewById(R.id.iv_changyong_two);
        iv_changyong_three = (ImageView) view.findViewById(R.id.iv_changyong_three);
        iv_changyong_four = (ImageView) view.findViewById(R.id.iv_changyong_four);
        iv_changyong_five = (ImageView) view.findViewById(R.id.iv_changyong_five);
        tv_use_num_one = (TextView) view.findViewById(R.id.tv_use_num_one);
        tv_use_num_two = (TextView) view.findViewById(R.id.tv_use_num_two);
        tv_use_num_three = (TextView) view.findViewById(R.id.tv_use_num_three);
        tv_use_num_four = (TextView) view.findViewById(R.id.tv_use_num_four);
        tv_use_num_five = (TextView) view.findViewById(R.id.tv_use_num_five);
        tv_win_num_one = (TextView) view.findViewById(R.id.tv_win_num_one);
        tv_win_num_two = (TextView) view.findViewById(R.id.tv_win_num_two);
        tv_win_num_three = (TextView) view.findViewById(R.id.tv_win_num_three);
        tv_win_num_four = (TextView) view.findViewById(R.id.tv_win_num_four);
        tv_win_num_five = (TextView) view.findViewById(R.id.tv_win_num_five);
        my_history_fragment_listview = (ListView) view.findViewById(R.id.my_history_fragment_listview);
        tv_to_all_history= (TextView) view.findViewById(R.id.tv_to_all_history);
        tv_to_all_history.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent_tv_to_all_history=new Intent(getActivity(),AllHisttoryActivity.class);
                startActivity(intent_tv_to_all_history);
            }
        });

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            for (int i = 1; i < 27; i++) {
                if (server_id[i].equals(findHistotySummoner.getData().getData().getArea() + "") == true) {
                    flag = i;
                }
            }
            tv_show_play_nicker_name.setText(findHistotySummoner.getData().getData().getName());
            tv_show_play_area.setText(server_name[flag]);
            Picasso.with(getActivity()).load(findHistotySummoner.getData().getData().getIcon_url()).into(show_play_icon);
        }
    };
    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            acount_one.setText("场次:" + zhanjigailan.getData().getData().get(0).getTotal_num());
            win_acount_one.setText("胜场:" + zhanjigailan.getData().getData().get(0).getWin_num());
            acount_two.setText("场次:" + zhanjigailan.getData().getData().get(1).getTotal_num());
            win_acount_two.setText("胜场:" + zhanjigailan.getData().getData().get(1).getWin_num());
            acount_three.setText("场次:" + zhanjigailan.getData().getData().get(2).getTotal_num());
            win_acount_three.setText("胜场:" + zhanjigailan.getData().getData().get(2).getWin_num());
            acount_four.setText("场次:" + zhanjigailan.getData().getData().get(3).getTotal_num());
            win_acount_four.setText("胜场:" + zhanjigailan.getData().getData().get(3).getWin_num());
            donutProgress_one.setDonut_progress(zhanjigailan.getData().getData().get(0).getWin_num() * 100 / zhanjigailan.getData().getData().get(0).getTotal_num() + "");
            donutProgress_one.setProgress(zhanjigailan.getData().getData().get(0).getWin_num() * 100 / zhanjigailan.getData().getData().get(0).getTotal_num());
            donutProgress_two.setDonut_progress(zhanjigailan.getData().getData().get(1).getWin_num() * 100 / zhanjigailan.getData().getData().get(1).getTotal_num() + "");
            donutProgress_two.setProgress(zhanjigailan.getData().getData().get(1).getWin_num() * 100 / zhanjigailan.getData().getData().get(1).getTotal_num());
            donutProgress_three.setDonut_progress(zhanjigailan.getData().getData().get(2).getWin_num() * 100 / zhanjigailan.getData().getData().get(2).getTotal_num() + "");
            donutProgress_three.setProgress(zhanjigailan.getData().getData().get(2).getWin_num() * 100 / zhanjigailan.getData().getData().get(2).getTotal_num());
            donutProgress_four.setDonut_progress(zhanjigailan.getData().getData().get(3).getWin_num() * 100 / zhanjigailan.getData().getData().get(3).getTotal_num() + "");
            donutProgress_four.setProgress(zhanjigailan.getData().getData().get(3).getWin_num() * 100 / zhanjigailan.getData().getData().get(3).getTotal_num());
        }
    };
    private Handler handler3 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String result = readFile("hero/heroTgpIds.json");
            try {
                JSONObject object = new JSONObject(result);
                String id_one = object.getString(changYongYingXiong.getData().getData().get(0).getChampion_id() + "");
                String id_two = object.getString(changYongYingXiong.getData().getData().get(1).getChampion_id() + "");
                String id_three = object.getString(changYongYingXiong.getData().getData().get(2).getChampion_id() + "");
                String id_four = object.getString(changYongYingXiong.getData().getData().get(3).getChampion_id() + "");
                String id_five = object.getString(changYongYingXiong.getData().getData().get(4).getChampion_id() + "");
                String hero_result_one = readFile("hero/" + id_one + ".json");
                String hero_result_two = readFile("hero/" + id_two + ".json");
                String hero_result_three = readFile("hero/" + id_three + ".json");
                String hero_result_four = readFile("hero/" + id_four + ".json");
                String hero_result_five = readFile("hero/" + id_five + ".json");
                JSONObject obj_one = new JSONObject(hero_result_one);
                JSONObject obj_two = new JSONObject(hero_result_two);
                JSONObject obj_three = new JSONObject(hero_result_three);
                JSONObject obj_four = new JSONObject(hero_result_four);
                JSONObject obj_five = new JSONObject(hero_result_five);
                Picasso.with(getActivity()).load(obj_one.getString("pic_url")).into(iv_changyong_one);
                Picasso.with(getActivity()).load(obj_two.getString("pic_url")).into(iv_changyong_two);
                Picasso.with(getActivity()).load(obj_three.getString("pic_url")).into(iv_changyong_three);
                Picasso.with(getActivity()).load(obj_four.getString("pic_url")).into(iv_changyong_four);
                Picasso.with(getActivity()).load(obj_five.getString("pic_url")).into(iv_changyong_five);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            tv_use_num_one.setText(" " + changYongYingXiong.getData().getData().get(0).getUse_num() + "场");
            tv_use_num_two.setText(" " + changYongYingXiong.getData().getData().get(1).getUse_num() + "场");
            tv_use_num_three.setText(" " + changYongYingXiong.getData().getData().get(2).getUse_num() + "场");
            tv_use_num_four.setText(" " + changYongYingXiong.getData().getData().get(3).getUse_num() + "场");
            tv_use_num_five.setText(" " + changYongYingXiong.getData().getData().get(4).getUse_num() + "场");
            tv_win_num_one.setText(changYongYingXiong.getData().getData().get(0).getWin_num() * 100 / changYongYingXiong.getData().getData().get(0).getUse_num() + "%胜率");
            tv_win_num_two.setText(changYongYingXiong.getData().getData().get(1).getWin_num() * 100 / changYongYingXiong.getData().getData().get(1).getUse_num() + "%胜率");
            tv_win_num_three.setText(changYongYingXiong.getData().getData().get(2).getWin_num() * 100 / changYongYingXiong.getData().getData().get(2).getUse_num() + "%胜率");
            tv_win_num_four.setText(changYongYingXiong.getData().getData().get(3).getWin_num() * 100 / changYongYingXiong.getData().getData().get(3).getUse_num() + "%胜率");
            tv_win_num_five.setText(changYongYingXiong.getData().getData().get(4).getWin_num() * 100 / changYongYingXiong.getData().getData().get(4).getUse_num() + "%胜率");
        }
    };
    private Handler handler4 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int totalHeight = 0;
            super.handleMessage(msg);
            adapter = new HistoryAdapter(getActivity(), recentBattle);
            for (int i = 0; i < adapter.getCount(); i++) {

                View listViewItem = adapter.getView(i, null, my_history_fragment_listview);
                listViewItem.measure(0, 0);
                totalHeight += listViewItem.getMeasuredHeight();
            }

            ViewGroup.LayoutParams params = my_history_fragment_listview.getLayoutParams();

            params.height = totalHeight + (my_history_fragment_listview.getDividerHeight() * (adapter.getCount() - 1));
            my_history_fragment_listview.setLayoutParams(params);
            my_history_fragment_listview.setAdapter(adapter);
        }
    };

    private String readFile(String fileName) {
        String result = "";
        try {
            // 读取assets中的文件，文件内容写入一个输入流里边
            InputStream is = getActivity().getAssets().open(fileName);
            // 按行读取
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            // 创建一个临时的字符串来保存每一行的数据
            String line = "";
            // 循环读取文件内容，每次读取一行，如果读取到文件末尾，则读取的内容为null
            while ((line = br.readLine()) != null) {
                result += line;// 将每次读取的内容给最终的result
            }
            // 关闭流,先开的关
            br.close();
            isr.close();
            is.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }
}
